package bank.service.spring.department;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import bank.model.dao.DepartmentDAO;
import bank.model.vo.Department;

public class ChooseDepartmentController implements Controller {
	
	public ChooseDepartmentController(DepartmentDAO departmentDAO) {
		super();
		this.departmentDAO = departmentDAO;
	}

	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse responce) throws Exception {
		System.out.println("This is ChooseDepartmentController");	
		request.setAttribute("enter", true);
		
		boolean error = false;
		
		int id = 0;
		try {
			String sid = request.getParameter("selectId");
			id = Integer.valueOf(sid);		

			if ((sid == null) || (id < 1)) {
				 //throw new Exception("No department selected");
				error = true;
				request.setAttribute("errorFlag", error);
				return new ModelAndView("department/choosedepartment");
			}		
		} catch (Exception e) {
			error = true;
			request.setAttribute("errorFlag", error);
			e.printStackTrace();
			return new ModelAndView("department/choosedepartment");			
		}
		
		Department dept = departmentDAO.findById(id);		
		request.setAttribute("dept", dept);
		
		final String ACT_ADD_SUB = "Add"; //TODO: normal names
		final String ACT_SHOW_EMP = "Show";
		final String ACT_DELETE = "Delete";		
		final String ACT_RENAME = "Rename";
		
		String control = "";
		control = request.getParameter("control_type");
		System.out.println(control);
				
		if ( control.equals(ACT_ADD_SUB) ) {
			String name = request.getParameter("addSub_text");
			if (name == null) 
				throw new Exception("Department must have name");
			departmentDAO.add(name, id);
			return new ModelAndView("department/newdepartment", "name", name);
		} else
		if (control.equals(ACT_DELETE)) {
			departmentDAO.delete(false, id);
			return new ModelAndView("department/choosedepartment", "action", 0); //TODO: replace 0 and 1
		} else
		if (control.equals(ACT_SHOW_EMP)) {
			//TODO: redirect to employees page
			throw new Exception("Employee list is not available by now");
		} else	
		if (control.equals(ACT_RENAME)) { //TODO: " in SQL builder
			String name = request.getParameter("rename_text");
			dept = new Department(id, name);
			departmentDAO.update(id, dept);
			return new ModelAndView("department/choosedepartment", "action", 1);
		} else
			throw new Exception ("Unknown action");		
	}
	
	private DepartmentDAO departmentDAO;	
}
